import { useEffect, useState } from 'react';
import { Alert, Linking, PermissionsAndroid, Platform } from 'react-native';
import { BleManager } from 'react-native-ble-plx';

// 蓝牙步骤：1️⃣ 先拿权限 → 2️⃣ 真正建立连接 → 3️⃣ 发现服务与特征值。

// 单例模式
class BLEServiceInstance {
  manager: BleManager

  constructor() {
    this.manager = new BleManager()
  }
}

const checkLocationServices = async () => {
  // 这里简化处理，实际可能需要更复杂的检查
  try {
    // 尝试打开位置服务设置
    await Linking.openSettings();
  } catch (error) {
    console.log('无法打开设置:', error);
  }
};

export const BLEService = new BLEServiceInstance()

/* ---------- 1. 权限 ---------- */
export const requestBluetoothPermission = async () => {
  try {
    if (Platform.OS === 'ios') {
      return true
    }
    if (Platform.OS === 'android' && PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) {
      const apiLevel = parseInt(Platform.Version.toString(), 10)
   
      if (apiLevel < 31) {
        const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
        return granted === PermissionsAndroid.RESULTS.GRANTED
      }

      if (PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN && PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT) {
        const result = await PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
          PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
        ])
  
        return (
          result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
          result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
          result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED
        )
      }
    }
  
    Alert.alert(
      '需要开启定位服务',
      '蓝牙功能需要位置服务支持，请开启定位服务',
      [
        { text: '取消', style: 'cancel' },
        { text: '去设置', onPress: () => checkLocationServices() }
      ]
    );
    return false
  } catch (error) {
    console.log(error, '蓝牙报错啦')
  }
}


/* ---------- 2. 完整连接流程 ---------- */
export const baseConnectDevice = async (deviceId: string) => {
  try {
    console.log(BLEService.manager.connectToDevice, 'BLEService.manager')
    const device = await BLEService.manager.connectToDevice(deviceId);
    await device.discoverAllServicesAndCharacteristics();
    console.log('已连接', device.name, device.id);
    return device;
  } catch (error) {
    console.error('连接失败', error);
    throw error;
  }
};

/* ---------- 3. 扫描 + 自动连接示例 ---------- */
export const useBluetooth = () => {

  const [Linking, setLinking] = useState<boolean>(false)
  const [devices, setDevices] = useState<any[]>([]);
  const [connected, setConnected] = useState<any | null>(null);

  useEffect(() => {

    let sub: any;
    (async () => {

      const ok = await requestBluetoothPermission();
      if (!ok) {
        console.log('用户拒绝权限');
        return;
      }

      if (!BLEService?.manager) {
        console.error('蓝牙服务未初始化');
        return;
      }

      sub = BLEService.manager.onStateChange((state) => {
        if (state === 'PoweredOn') {

          BLEService.manager.startDeviceScan(null, { allowDuplicates: false },
            async (error, device) => {
              if (error) {
                console.error('扫描错误', error);
                BLEService.manager.stopDeviceScan();
                return;
              }

              if (device) {
                setDevices((prev) => {
                  const exists = prev.find((d) => d.id === device.id);
                  return exists ? prev : [...prev, device];
                });

              }
            },
          );
        }
      }, true);
    })();

    return () => {
      sub?.remove();
      BLEService.manager.stopDeviceScan();
    };
  }, [BLEService.manager]);

  // 新增：手动连接函数
  const connectDevice = async (deviceId: string) => {
    try {
      setLinking(true)
      BLEService.manager.stopDeviceScan();
      const dev = await baseConnectDevice(deviceId);
      setConnected(dev);
    } catch (e) {
      Alert.alert('连接失败', (e as any).message);
    } finally {
      setLinking(false)
    }
  };

  // 调试蓝牙连接问题
  const debugConnect = async (deviceId: string) => {
    try {
      // 1️⃣ 蓝牙状态
      const state = await BLEService.manager.state();
      console.log('🔍 蓝牙状态:', state); // 必须是 PoweredOn
      if (state !== 'PoweredOn') {
        Alert.alert('请先打开蓝牙');
        return;
      }
  
      // 2️⃣ 权限（Android 12+ 才需要）
      if (Platform.OS === 'android') {
        const granted = await PermissionsAndroid.check(
          'android.permission.BLUETOOTH_CONNECT',
        );
        console.log('🔐 BLUETOOTH_CONNECT 权限:', granted); // true
        if (!granted) {
          Alert.alert('蓝牙连接权限未授予');
          return;
        }
      }
  
      // 3️⃣ 设备是否已连接
      const already = await BLEService.manager.isDeviceConnected(deviceId);
      console.log('🔗 已连接?', already);
      if (already) {
        Alert.alert('设备已连接');
        return;
      }
  
      // 4️⃣ 停止扫描（iOS 必须）
      BLEService.manager.stopDeviceScan();
  
      // 5️⃣ 真正连接 + 超时
      console.log('🚀 开始连接:', deviceId);
      const device = await BLEService.manager.connectToDevice(deviceId, {
        timeout: 8000,
      });
      console.log('✅ 已连接', device.name, device.id);
      return device;
    } catch (e) {
      console.error('❌ 连接错误', e);
      Alert.alert('连接失败', e.message);
    }
  };

  // Linking：连接状态
  // devices：扫描的全部设备
  // connected：已连接设备
  // connectDevice：连接设备
  // debugConnect：调试连接
  return { Linking, devices, connected, connectDevice, debugConnect };
};